//
//  JDActionSheetContentView.swift
//  funcode
//
//  Created by Wan Jiading on 2017/2/22.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit

extension JDActionSheet {

	
	func setupTableView(_ bookList: [Book], _ superView: UIView) {
		
		let b1 = Book()
		b1.book_name = "time for bed"
		b1.available_play = "1"
		let a1 = Audio()
		a1.audio_type_name = "歌曲"
		b1.audio = a1
		
		let b2 = Book()
		b2.book_name = "good night moon"
		b2.available_play = "0"
		let a2 = Audio()
		a2.audio_type_name = "哄睡"
		b2.audio = a2
		
		
		dataList = [b1, b2]
		
		for index in 0..<200 {
			getBook(index)
		}
		
		
		self.tableView = UITableView(frame: superView.bounds)
		self.tableView!.backgroundColor = UIColor.clear
		self.tableView!.dataSource = self
		self.tableView!.delegate = self
		self.tableView!.separatorColor = UIColor.rgb("e6e6e6")
		self.tableView!.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
		self.tableView!.tableFooterView = UIView()
		self.tableView!.register(UINib.init(nibName: "JDActionContentCell", bundle: nil), forCellReuseIdentifier: cellID)
		superView.addSubview(self.tableView!)
		
	}
	
	func getBook(_ index: Int) {
		
		let b2 = Book()
		b2.book_name = "\(index) good night moon good night moon good night moon "
		
		let random = arc4random_uniform(1000)
		if random % 3 == 2 {
			b2.available_play = "0"
		} else {
			b2.available_play = "1"
		}
		
		let a2 = Audio()
		a2.audio_type_name = "\(random)哄睡"
		b2.audio = a2
		
		dataList?.append(b2)
	}
	
    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
		return dataList?.count ?? 0 > 0 ? 1 : 0
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return dataList?.count ?? 0
    }
	
	func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
		return 45
	}
	
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! JDActionContentCell
		cell.book = dataList![indexPath.row]
		if indexPath.row == currentSelectedIndex {
			cell.didSelected(true)
		} else {
			cell.didSelected(false)
		}
		cell.selectionStyle = .none;
		return cell
	}
	
	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		if self.delegate != nil && self.delegate!.responds(to: #selector(JDActionSheetDelegate.actionSheet(_:indexDidClick:))) {
			
			if currentSelectedIndex > -1 {
				let oldCell = tableView.cellForRow(at: IndexPath(row: currentSelectedIndex, section: 0)) as? JDActionContentCell
				oldCell?.didSelected(false)
			}
			
			let newCell = tableView.cellForRow(at: indexPath) as! JDActionContentCell
			newCell.didSelected(true)
			
			self.delegate!.actionSheet!(self, indexDidClick: indexPath.row)
		}
	}
}
